<script setup lang="ts">
import type { FormInstance, FormValidateCallback } from 'element-plus'
import type { EaBillboard } from './type'

const baseApi = '/ea/ea-billboard'

defineProps<{
  // 禁用表单内的所有组件
  disabled?: boolean
  // 禁用属性列表（只读不可输入）
  disabledProps?: string[]
  // 不可见属性列表（忽略不加载）
  invisibleProps?: string[]
}>()

const emit = defineEmits<{
  (e: 'complete', id?: string, isNew?: boolean): void
  (e: 'submitting', submitting: boolean): void
}>()

const { initRelatedData, relatedData } = useOption({
  dict: ['billboard_type']
})

const { loadData, loading, model } = useDetail<EaBillboard>(baseApi)

const { submitting, submit } = useForm({ baseApi, successCallback: (id, isNew) => emit('complete', id, isNew) })
watch(submitting, value => emit('submitting', value))

//  表单
const formRef = ref<FormInstance>()

const validate = (
  callback: FormValidateCallback = (valid: boolean) =>
    !valid && ElMessage.error({ message: '表单校验不通过', grouping: true })
) =>
  Promise.all([formRef.value].map(e => e?.validate?.(callback)).filter(e => !!e))
    .then((arr: (boolean | undefined)[]) => arr.every(e => e))
    .catch(() => false)

defineExpose({
  init: (id?: string, refresh = true, initData?: Record<string, unknown>) => {
    // 初始化选项
    initRelatedData()
    if (model.value.id === id && !refresh) return
    // 加载数据
    loadData(id).then(() => {
      if (!id) {
        if (initData)
          Object.keys(initData).forEach(key => (model.value[key as keyof EaBillboard] = initData[key] as any))
      }
    })
  },
  validate,
  getData: async (relatedLabel = false) => {
    const data: Record<string, unknown> = _.cloneDeep(model.value)
    if (!relatedLabel) return data

    data.billboardTypeLabel = relatedData.billboardTypeOptions.find(e => e.value === data.billboardType)

    return data
  },
  submit: () => submit(model.value, formRef.value),
  reset: () => {
    formRef.value?.resetFields()
    model.value.id = void 0
  }
})
</script>

<template>
  <el-form ref="formRef" v-loading="loading" :model="model" label-width="90px" :disabled="disabled">
    <el-row :gutter="18">
      <el-col v-if="!invisibleProps?.includes('billboardType')" :span="24">
        <el-form-item prop="billboardType" label="榜单类型">
          <el-select
            v-model="model.billboardType"
            :disabled="disabledProps?.includes('billboardType')"
            filterable
            clearable
          >
            <el-option v-for="item in relatedData.billboardTypeOptions" :key="item.value" v-bind="item" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('content')" :span="24">
        <el-form-item prop="content" label="内容">
          <el-input v-model="model.content" :disabled="disabledProps?.includes('content')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workerId')" :span="24">
        <el-form-item prop="workerId" label="工人Id">
          <el-input v-model="model.workerId" :disabled="disabledProps?.includes('workerId')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workerName')" :span="24">
        <el-form-item prop="workerName" label="工人名称">
          <el-input v-model="model.workerName" :disabled="disabledProps?.includes('workerName')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('gainTime')" :span="24">
        <el-form-item prop="gainTime" label="获得时间">
          <el-input v-model="model.gainTime" :disabled="disabledProps?.includes('gainTime')" clearable />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
